package com.dream.jump.data

import androidx.datastore.preferences.core.Preferences
import com.dream.jump.entity.model.LoggedInUser
import com.dream.jump.entity.model.LoginParam
import com.dream.jump.file.FileConfig
import com.dream.jump.file.SystemConfig
import com.dream.jump.retrofit.RetrofitApi
import com.dream.jump.room.TypeDao
import com.dream.jump.room.TypeEntity
import com.dream.jump.room.UserDao
import retrofit2.Retrofit
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class DataRepository @Inject constructor(
    private val dataStoreClient: DataStoreClient,
    private val fileConfig: FileConfig,
    private val retrofitBuilder: Retrofit.Builder,
    private val typeDao: TypeDao,
    private val userDao: UserDao
) {
    lateinit var platformRetrofitApi: RetrofitApi
    lateinit var orderRetrofitApi: RetrofitApi
    lateinit var fileRetrofitApi: RetrofitApi

    companion object UserInfo {
        var userId = 0
        var token = ""
    }

    fun initRetrofitApi(systemConfig: SystemConfig) {
        platformRetrofitApi = retrofitBuilder.baseUrl(systemConfig.platformServerUri).build()
            .create(RetrofitApi::class.java)
        orderRetrofitApi = retrofitBuilder.baseUrl(systemConfig.dataServerUri).build()
            .create(RetrofitApi::class.java)
        fileRetrofitApi = retrofitBuilder.baseUrl(systemConfig.fileServerUri).build()
            .create(RetrofitApi::class.java)
    }

    suspend fun getDataStore(key: Preferences.Key<String>): String {
        return dataStoreClient.getValueByKey(key)
    }

    suspend fun putDataStore(mapValue: Map<Preferences.Key<String>, String>) {
        return dataStoreClient.putDataStore(mapValue);
    }

    suspend fun login(loginParam: LoginParam) = platformRetrofitApi.login(loginParam).parseData()

    suspend fun loadFunction() = platformRetrofitApi.loadFunction(token, userId).parseData()

    suspend fun loadOrderTypes(operateCode: String) =
        orderRetrofitApi.loadOrderTypes(token, operateCode).parseData()

    suspend fun insertOrReplaceType(typeEntity: TypeEntity) =
        typeDao.insertOrReplaceType(typeEntity)

    suspend fun selectAllType() = typeDao.selectAllType()

}
